#include <51func.h>
int main(int argc, char *argv[])
{
    // ./8_aqiang_select 1.pipe 2.pipe 
    ARGS_CHECK(argc,3);
    int fdr = open(argv[1],O_RDONLY);
    ERROR_CHECK(fdr,-1,"open fdr");
    int fdw = open(argv[2],O_WRONLY);
    ERROR_CHECK(fdw,-1,"open fdw");
    printf("chat1 is established!\n");
    char buf[4096];
    // 设置监听
    // 申请内存
    fd_set rdset; // read set
    while(1){
        // 初始化
        FD_ZERO(&rdset);
        // 将感兴趣的文件描述符加入监听集合
        FD_SET(STDIN_FILENO,&rdset);
        FD_SET(fdr,&rdset);
        // OS轮询 进程等待
        select(fdr+1,&rdset,NULL,NULL,NULL);
        // fdr或者stdin就绪，进程从select返回，得到一个就绪集合
        // select的设计当中，就绪集合和监听集合使用同一地址
        // 依次检查fdr和stdin是否就绪
        if(FD_ISSET(STDIN_FILENO,&rdset)){
            memset(buf,0,sizeof(buf));
            ssize_t sret = read(STDIN_FILENO,buf,sizeof(buf));
            if(sret == 0){
                write(fdw,"nishigehaoren",13);
                break;
            }
            write(fdw,buf,strlen(buf));
        }
        if(FD_ISSET(fdr,&rdset)){
            memset(buf,0,sizeof(buf));
            ssize_t sret = read(fdr,buf,sizeof(buf));
            if(sret == 0){
                printf("hehe!\n");
                break;
            }
            printf("buf = %s\n", buf);
        }
    }
    close(fdr);
    close(fdw);
    return 0;
}

